package com.cman777.springc.logger.plugin;

import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.filter.AbstractFilter;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author chenzhicong
 * @time 2019/11/7 22:17
 * @description
 * spring cloud有大量的‘没用’的debug日志，而我们的其他业务也有debug日志。
 * spring cloud由于心跳的存在，造成debug日志一直在刷，看起来很烦。
 * 所以这个类的作用就是把 spring cloud日志单独放到一个日志文件里面
 * https://blog.csdn.net/zhanngle/article/details/79264656?utm_source=blogxgwz1
 */
@Plugin(name = "SpringCloudPlugin", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE, printObject = true)
public class SpringCloudPlugin extends AbstractFilter {

    /**
     *
     */
    private static final List<String> SPRING_CLOUD_THREAD_NAME_LIST = Collections.unmodifiableList(
            Arrays.asList("DiscoveryClient","PollingServerListUpdater","Eureka","Feign"
                    ,"NFLoadBalancer","AsyncResolver"));

    protected SpringCloudPlugin() {
        super();
    }

    protected SpringCloudPlugin(Result onMatch, Result onMismatch) {
        super(onMatch, onMismatch);
    }

    @Override
    public Result filter(LogEvent event) {
        /*获取线程名称，过滤掉SPRING_CLOUD_THREAD_NAME_LIST中的*/
        for (String x : SPRING_CLOUD_THREAD_NAME_LIST) {
            if (event.getThreadName().startsWith(x)) {
                return this.onMatch;
            }
        }
        return this.onMismatch;
    }

    /**
     *
     * @param match
     * @param mismatch
     * @return
     */
    @PluginFactory
    public static SpringCloudPlugin createFilter(
            @PluginAttribute("onMatch") final Result match,
            @PluginAttribute("onMismatch") final Result mismatch) {
        return new SpringCloudPlugin(match, mismatch);
    }



}
